package cz.muni.fi.pb138.srgsxmldb.validator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * This class provides validation of SRGS XML file against grammar schema
 * available at http://www.w3.org/TR/speech-grammar/#AppC
 * 
 * @author 5-ka
 * 
 */
public class ValidatorSRGS {
    private Schema schema;
    private Validator validator;
    
    /**
     * Creates a schema object from internal XSD schema file
     * and its validator.
     * @throws SAXException if schema creation fails
     * @throws FileNotFoundException if XSD schema file not found
     */
    public ValidatorSRGS() {
        
        SchemaFactory xsFact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            
            File file = new File ("grammar.xsd");
            schema = xsFact.newSchema(new StreamSource(new FileInputStream(file)));
                
        } catch (SAXException ex) {
            Logger.getLogger(ValidatorSRGS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ValidatorSRGS.class.getName()).log(Level.SEVERE, null, ex);
        }
        validator = schema.newValidator();
    }
    
    /**
     * this method validates document from parameter
     * @param input parsed XML grammar document to validate
     * @return true if input document is valid against official schema
     */
    public boolean validate(Document input) {
        try {
            DOMSource source = new DOMSource(input);
            validator.validate(source);
            return true;
        } catch (SAXException ex) {
            System.out.println("invalid - dovod: " + ex.getLocalizedMessage());
            return false;
        } catch (IOException ex) {
            Logger.getLogger(ValidatorSRGS.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("invalid - other reason");
            return false;
        }
    }  
}
